package testThrift;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Arrays;

import org.apache.thrift.TException;
import org.apache.thrift.protocol.TProtocol;
import org.apache.thrift.transport.TMemoryBuffer;

public class testThrift {

	public static void main(String[] args) throws TException, IOException {
		// use setXX to construct an object
		TestMessage testMessage1 = new TestMessage();
		testMessage1.setDate("this is data1");
		testMessage1.setText("this is text1");
		
		// use constructor
		TestMessage testMessage2 = new TestMessage("this is data2", "this is text2");
		
		// 申请内存 TMemoryBuffer
		TMemoryBuffer mb0 = new TMemoryBuffer(32);
		
		// TBinaryProtocol 转化成为二进制
		// TCompactProtocol 转化成二进制并进行压缩
		// 在内存上构建TCompactProtocol
		TProtocol prot0 = new org.apache.thrift.protocol.TBinaryProtocol(mb0);
		
		//TProtocol prot1 = new org.apache.thrift.protocol.TJSONProtocol(mb1);
		
		// 序列化
		// 将testMessage1序列化到prot0@mb0
		testMessage1.write(prot0);
		System.out.println("Binary length：" + mb0.length());

		// 反序列化,获得的data长度会比真正的数据大，实际数据长度是mb0.length()，末尾用0填充
		byte[] data = mb0.getArray();
		System.out.println("data length：" + data.length);
		data = Arrays.copyOf(data, mb0.length());
		System.out.println("data actual length：" + data.length);
		
		{
			TMemoryBuffer readMB = new TMemoryBuffer(32);
			TProtocol tp = new org.apache.thrift.protocol.TBinaryProtocol(readMB);
			readMB.write(data);
			//ByteBuffer buf = ByteBuffer.wrap(data);
			//tp.writeBinary(buf);
			TestMessage deserMessage1 = new TestMessage();
			deserMessage1.read(tp);
			System.out.println("After Deserialize：" + deserMessage1.getDate() + " " + deserMessage1.getText());
		}
		// 写入到文件test
		DataOutputStream out = new DataOutputStream(new FileOutputStream("test"));
		out.write(data);
		out.close();
		
		// 读文件
		DataInputStream  in = new DataInputStream(new FileInputStream("test"));
		// 为了测试，设置1024读取所有文件内容,否则应该循环调用读取文件内容
		byte[] readdata = new byte[1024];
		in.read(readdata);
		{
			TMemoryBuffer readMB = new TMemoryBuffer(32);
			readMB.write(data);
			TProtocol tp = new org.apache.thrift.protocol.TBinaryProtocol(readMB);
			TestMessage deserMessage1 = new TestMessage();
			deserMessage1.read(tp);
			System.out.println("After ReadFile：" + deserMessage1.getDate() + " " + deserMessage1.getText());
		}		
	}

}
